<?php


namespace app\api\controller\v1;

use app\controller\Base;
use app\model\User as UserModel;
use think\facade\Validate;
use think\Request;


/**
 * Class User
 * @package app\controller
 */
class User extends Base
{
    //关联数据一对多，根据用户表中ID查看对应发表的文章

    /**
     * @param $id
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index($id){

        if(!Validate::isInteger($id)){
            return $this->create([],'参数不合法~',400);
        }

        $data = UserModel::find($id);//查询用户表

        if (empty($data)){

            return $this->create([],'no',204);

        }else{

            //返回关联用户在文章表中的数据：查询某个用户发布的所有文章
            //article属性模式；article()方法模式
            //return $this->create($data->article,'ok',200);
            //也可以直接拼接到$data上，但是结果就变成数据集了
            return $this->create($data->article()->field('id,title,title_img,content,user_id')->page($this->page,$this->pageSize)->select(),'ok',200);
        }

    }

    //登录持久化

    /**
     * @param Request $request
     * @return \think\Response
     */
    public function CheckLogin(Request $request){

        $data = $request->param();
        $result = Validate::rule([
            'name'=>'unique:User,name^password'
            //规则说明：用户名和密码在数据表user（不包含前缀，跟引入的模型无关）中唯一
        ])->check([
            'name'=> $data['name'],
            'password'=>sha1($data['password']),
        ]);

        if(!$result){
            session('admin',$data['name']);
            return $this->create(true,'登录成功',200);
        }else{
            return $this->create([],'登录失败',400);
        }

        //return $this->create($request->param(),'ok');
    }

    public function test(Request $request){
        return json($request->param());
    }
}